<?php

	namespace ai\engine;

	use GuzzleHttp\Client;
	use GuzzleHttp\Exception\GuzzleException;

	class Dify extends Server{
		private $config;

		/**
		 * 构造方法
		 * WxPay constructor.
		 * @param $config
		 */
		public function __construct($config = [])
		{
			$this->config = $config;
		}

		public function streamReply($user,$question,$stream = true){
			if($stream){
				// 开启输出缓冲
				ob_start();
			}
			try {
				$guzzle = new Client();
				$response = $guzzle->request("POST", $this->config['host'].'/v1/chat-messages', [
					'headers' => [
					  'Authorization' => 'Bearer '.$this->config['api_key'],
					],
					'json' => [
						'inputs' => [],
						'query' => $question,
						'response_mode' => 'streaming',
						'conversation_id' => '',
						'user' => $user,
					],
					'stream' => true,
				]);

				$body = $response->getBody();
				$buffer = '';

				while (!$body->eof()) {
					$buffer .= $body->read(128);
					// 这里使用 while 是因为读取 n 个字节有可能同时读出 n 条 EventSource 消息
					while (($pos = strpos($buffer, "\n\n")) !== false) {

						$msg = substr($buffer, 0, $pos); // 一条 event 消息
						$buffer = substr($buffer, $pos + 2); // 去除已被解析的部分

						if (substr($msg, 0, 6) === 'data: ') { // 只解析了 data ，实际的 EventSource 还有 event 、id 、retry
							$obj = json_decode(substr($msg, 6));
							switch($obj->event){
								case 'agent_message':
									if($stream){
										$data = ['answer' => $obj->answer];
										echo "data: ".json_encode($data)."\n\n";
										ob_flush();
										flush();
									}
									break;
								case 'agent_thought':
									$reply = $obj->thought;
									break;
								case 'message':
									$data = ['answer' => $obj->answer];
									echo "data: ".json_encode($data)."\n\n";
									ob_flush();
									flush();
									break;
							}
						}
					}
				}

				if($stream){
					echo "event: end\n";
					echo "data: Stream ended\n\n";
				}

				if($reply) return $reply;
			} catch (GuzzleException $e) {
				return response('请求失败，请稍后重试', 500);
			}
		}
		public function textReply($user,$question,$conversation_id = ''){
			try {
				$guzzle = new Client();
				$response = $guzzle->request("POST", $this->config['host'].'/v1/chat-messages', [
					'headers' => [
					  'Authorization' => 'Bearer '.$this->config['api_key'],
					],
					'json' => [
						'inputs' => [],
						'query' => $question,
						'response_mode' => 'blocking',
						'conversation_id' => $conversation_id,
						'user' => $user,
					],
					'stream' => true,
				]);

				$body = $response->getBody();
				$result = json_decode($body->getContents(), true);
				return $result;
			} catch (GuzzleException $e) {
				return response('请求失败，请稍后重试', 500);
			}
		}
	}